﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Models;
using Web.Areas.Mobile.Lib;
using DbUtility;
using Common.ModelBinders;
using Web.Areas.Mobile.Filter;

namespace Web.Areas.Mobile.Controllers
{
    [IsRegister]
    public class SurveyController : BaseController
    {
        public ActionResult Mark()
        {
            playerLogic pl = new playerLogic();
            scorelogLogic sl = new scorelogLogic();

            var dbPlayer = pl.Getplayer(new player { isopen = true });
            if (dbPlayer == null)
            {
                return RedirectToAction("NotOpen", "Survey", new { Area = "Mobile", msg = "<span class=\"player-name\">打分</span>暂未开始，请等待！" });
            }
            var dbScoreLog = sl.Getscorelog(new scorelog { userid = MobileAccount.ID, playerid = dbPlayer.id });
            if (dbScoreLog != null)
            {
                return RedirectToAction("NotOpen", "Survey", new { Area = "Mobile", msg = "您已经打过分了！" });
            }
            scorelog log = new scorelog() { playerid = dbPlayer.id };
            ViewBag.PlayerSort = dbPlayer.sort;
            return View(log);
        }
        [HttpPost]
        public ActionResult Mark(scorelog log)
        {
            try
            {
                DBContext db = new DBContext();
                playerLogic pl = new playerLogic();
                scorelogLogic sl = new scorelogLogic();
                wx_usersLogic ul = new wx_usersLogic();
                var dbUser = ul.Getwx_users(MobileAccount.ID);

                var dbPlayer = pl.Getplayer(log.playerid);
                if (!dbPlayer.isopen)
                {
                    return ErrorMsg("该选手评分已关闭！");
                }
                if (log.score < 80 || log.score > 100)
                {
                    return ErrorMsg("请输入 80-100 之间的分数！");
                }
                log.createdate = DateTime.Now;
                log.createuserid = log.userid = MobileAccount.ID;
                log.type = dbUser.GetUserType();
                var result = sl.Add(log);
                if (result)
                {
                    //更新参赛者的平均分
                    var r = db.ExecuteNonQuerySql(string.Format("update player set average= cast(round((select ISNULL(avg(score),0) from scorelog where playerid=player.id),2) as numeric(20,2)) where player.id={0}", dbPlayer.id));
                    return SuccessMsg("感谢您的评分！");
                }
                else
                {
                    return ErrorMsg("评分失败，网络错误！");
                }
            }
            catch (Exception e)
            {
                return ErrorMsg(e.Message);
            }
        }
        public ActionResult PlayerList()
        {
            playerLogic pl = new playerLogic();
            var list = pl.Getplayers(new player());
            return View(list);
        }
        public ActionResult Answer()
        {
            useranswerLogic ual = new useranswerLogic();
            questionLogic ql = new questionLogic();
            optionLogic ol = new optionLogic();
            areaLogic al = new areaLogic();
            if (MobileAccount.GetUser.type == (int)UserType.None)
            {
                return Redirect("/mobile/user/register");
            }
            var dbUserAnswers = ual.Getuseranswers(new useranswer { userid = MobileAccount.ID });
            var questions = ql.Getquestions(new question()).OrderBy(o => o.sort).ToList();
            if (questions.Count <= 0)
            {
                return RedirectToAction("NotOpen", "Survey", new { Area = "Mobile", msg = "<span class=\"player-name\">调研</span>暂未开始，请等待！" });
            }
            foreach (var q in questions)
            {
                q.options = ol.Getoptions(new option { questionid = q.id }).OrderBy(o => o.sort).ToList();
            }
            ViewBag.Provinces = al.Getareas(new area { depth = 0 });
            ViewBag.UserAnswers = dbUserAnswers;
            return View(questions);
        }
        [HttpPost]
        public ActionResult Answer([ModelBinder(typeof(JsonBinder<useranswer>))]List<useranswer> answers)
        {
            try
            {
                useranswerLogic ual = new useranswerLogic();

                var dbUserAnswers = ual.Getuseranswers(new useranswer { userid = MobileAccount.ID });
                if (dbUserAnswers.Count > 0)
                {
                    return ErrorMsg("您已经参加过调研了");
                }

                var now = DateTime.Now;
                foreach (var answer in answers)
                {
                    answer.createdate = now;
                    answer.createuserid = answer.userid = MobileAccount.ID;
                    var result = ual.Add(answer);
                }
                return SuccessMsg("提交成功！");
            }
            catch (Exception e)
            {
                return ErrorMsg(e.Message);
            }
        }

        [NotCheckIsRegister]
        [HttpGet]
        [ValidateInput(false)]
        public ActionResult NotOpen(string msg)
        {
            ViewBag.Msg = msg;
            return View();
        }
        [HttpPost]
        public ActionResult GetCity(string province)
        {
            try
            {
                areaLogic al = new areaLogic();
                var dbProvince = al.Getarea(new area { cname = province });
                var citys = al.Getareas(new area { parentid = dbProvince.id });
                return SuccessMsg(citys);
            }
            catch (Exception e)
            {
                return ErrorMsg(e.Message);
            }
        }
    }
}
